<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTool :shou-before="true">
        <template v-slot:after>
          <el-button type="primary" size="small" @click="inportFn">导入</el-button>
          <el-button type="primary" size="small" @click="exportFn">导出</el-button>
          <el-button type="primary" size="small" @click="addEmployess">新增员工</el-button>
        </template>
      </PageTool>
      <el-card>
        <!-- 表格 -->
        <el-table :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto" width="120px">
            <template v-slot="{row}">
              <!-- require('文件路径') -->
              <img
                v-imgError="require('@/assets/common/bigUserHeader.png')"
                style="width: 100px"
                :src="row.staffPhoto"
                alt=""
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="enableState">
            <template v-slot="{row}">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="enableState">
            <template v-slot="{row}">
              <el-button type="text" @click="toDetail(row.id)">查看</el-button>
              <el-button type="text" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="center">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="currentPage"
          />
        </el-row>
      </el-card>
      <AddEmployees
        :show-dialog.sync="visibleDialog"
        @updateEvent="userList"
      />
      <AssignRole
        ref="assignRole"
        :show-dialog.sync="showDialog"
      />
    </div>
  </div>
</template>

<script>
import { userList, delEmployee } from '@/api/employees'
import employees from '@/api/constant/employees'
import AddEmployees from './componeets/addEmployess'
import AssignRole from './componeets/assignRole.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
export default {
  components: { AddEmployees, AssignRole },
  data() {
    return {
      employeesList: [],
      total: 0,
      page: 1,
      pageSize: 5,
      visibleDialog: false,
      showDialog: false
    }
  },
  created() {
    // 获取员工列表
    this.userList()
  },
  methods: {
    // 角色
    assignRole(id) {
      this.showDialog = true
      this.$refs.assignRole.getEmployeeDetail(id)
    },
    // 查看列表
    toDetail(id) {
      this.$router.push(`/employees/detail/${id}`)
    },
    // 格式化聘用形式
    formatEmployment(type) {
      const obj = employees.hireType.find(item => item.id === +type)
      return obj && obj.value || '未知'
    },
    // 获取员工列表
    async userList() {
      const res = await userList({
        page: this.page,
        size: this.pageSize
      })
      console.log(res)
      // 保存员工列表和总数量
      this.employeesList = res.data.data.rows
      this.total = res.data.data.total
    },
    // 分页处理，页面刷新列表
    currentPage(page) {
      this.page = page
      this.userList()
    },
    // 新增员工
    addEmployess() {
      this.visibleDialog = true
    },
    // 删除角色
    del(id) {
      this.$confirm('是否确定删除？', '提示', {
        type: 'warning'
      }).then(async() => {
        // 调用删除接口
        await delEmployee(id)
        // 当删除最后一页的最有一条数据的时候，我们更新列表请求上一页的数据，（因为当前页的数据已经被删完）
        if (this.employeesList.length === 1 && this.page !== 1) {
          // 当渲染的列表数据长度等于1的说明 当前页面只剩下最后一条数据了
          // 且当前页不能是第一页，否则减一就变为0了
          this.page--
        }
        // 刷新列表
        this.userList()
      }).catch(err => {
        console.log('点击了取消按钮：', err)
      })
    },
    // 导入按钮
    inportFn() {
      this.$router.push('/import')
    },
    // 导出按钮
    async exportFn() {
      const res = await userList({
        page: this.page, // 页码
        size: this.total// 请求总数量
      })
      console.log(135, res)
      // 数据转换
      const data = res.data.data.rows.map(item => {
        return this.objToArr(item)
      })
      console.log('转换 后的数据', data)
      const header = ['手机号码', '姓名', '入职日期', '转正日期', '工号']
      export_json_to_excel({
        header,
        data
      })
    },
    // 对象转换为数组
    objToArr(item) {
      const arr = []
      // 处理对象，转换数组
      const headers = {
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'correctionTime': '转正日期',
        'workNumber': '工号'
      }
      for (const key in headers) {
        const value = item[key]// 属性值对应的值
        arr.push(value)
      }
      return arr
    }
  }

}

</script>

<style lang="scss" scoped>
.el-card{
  margin-top: 20px;
}
</style>
